package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;

import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.ModuleMapper;

import com.sd365.permission.centre.entity.Module;
import com.sd365.permission.centre.pojo.dto.ModuleDTO;
import com.sd365.permission.centre.pojo.query.IdVersionQuery;
import com.sd365.permission.centre.pojo.query.ModuleQuery;
import com.sd365.permission.centre.service.ModuleService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import com.sd365.permission.centre.service.util.SendMQMessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @author lenovo
 * @date 2022/07/081555
 **/
/**
 * @author wujiandong
 * @date 2022/08/17 14:17
 * @version 1.0.9
 * @description add方法 参数的tenantId、orgId、companyId等属性进行填充
 */
@Service
public class ModuleServiceImpl extends AbstractBaseDataServiceImpl implements ModuleService {

    @Autowired
    private SendMQMessageUtil sendMQMessageUtil;
    private static final String TABLE_NAME = "module";

    @Resource
    ModuleMapper moduleMapper;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public List<Module> commonQuery(ModuleQuery moduleQuery) {
        try {
            List<Module> modules = moduleMapper.commonQuery(moduleQuery);
            Page page = (Page) modules;
            BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
            System.out.println("service层commonQuery");
            return modules;
        } catch (Exception e) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MODULE_DB_EXCEPTION_CODE, e);
        }
    }

    @Override
    public Boolean add(@Valid ModuleDTO moduleDTO) {
        Module module = BeanUtil.copy(moduleDTO, Module.class);
        module.setId(idGenerator.snowflakeId());
        module.setVersion(1L);
        baseDataStuff4Add(module);
        module.setTenantId(BaseContextHolder.getTanentId());
        module.setOrgId(BaseContextHolder.getOrgId());
        module.setCompanyId(BaseContextHolder.getCompanyId());

        Boolean flag = moduleMapper.insert(module) > 0;
        if (flag) {
            sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, module);
        }
        return flag;
    }

    /**
     * 删除模块
     * @param id 模块id
     * @param version 版本
     * @return \\
     */
    @Override
    public Boolean remove(Long id, Long version) {
        Example example = new Example(Module.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
        try {
            Boolean flag = moduleMapper.deleteByExample(example)>0;
            if (flag) {
                Module module = new Module();
                module.setId(id);
                module.setVersion(version);
                sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, module);
            }
            return flag;
        } catch (Exception e) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MODULE_DB_EXCEPTION_CODE, e);
        }
    }

    /**
     * 批量删除列表
     * @param idVersionQueryList Module批量删除列表
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeBatch(List<IdVersionQuery> idVersionQueryList) {
        try {
            for (IdVersionQuery idVersionQuery : idVersionQueryList) {
                remove(idVersionQuery.getId(), idVersionQuery.getVersion());
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MODULE_DB_EXCEPTION_CODE, e);
        }
        return true;
    }

    @Override
    public Boolean modify(ModuleDTO moduleDTO) {
        Module module = BeanUtil.copy(moduleDTO, Module.class);
        baseDataStuff4Updated(module);
        Example example = new Example(Module.class);
        example.createCriteria().andEqualTo("id", moduleDTO.getId()).andEqualTo("version", moduleDTO.getVersion());
        module.setUpdatedTime(new Date());

        Boolean flag = moduleMapper.updateModule(module) > 0;
        if (flag) {
            sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, module);
        }
        return flag;
    }

    @Override
    public Boolean batchModify(ModuleDTO moduleDTO) {
        moduleDTO.setUpdatedTime(new Date());
        Module module = BeanUtil.copy(moduleDTO, Module.class);
        baseDataStuff4Updated(module);
        Example example = new Example(Module.class);
        example.createCriteria().andEqualTo("id", moduleDTO.getId()).andEqualTo("version", moduleDTO.getVersion());
        return moduleMapper.updateByExampleSelective(module, example) > 0;
    }

    @Override
    public ModuleDTO queryById(Long id) {
        try {
            ModuleDTO moduleDTO = null;
            Module module = moduleMapper.selectById(id);
            if (module != null) {
                moduleDTO = BeanUtil.copy(module, ModuleDTO.class);
            }
            return moduleDTO;
        } catch (BeanException ex){
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        }
    }
}
